package me.edzh.spring.bootstrap.utils.security;

import lombok.extern.log4j.Log4j;

import javax.xml.bind.DatatypeConverter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Edward on 2016/10/17.
 */
@Log4j
public class HashUtils {
    public static String SHA1(String decrypt) {
        try {
            MessageDigest digest = MessageDigest
                    .getInstance("SHA-1");
            digest.update(decrypt.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getMD5(String str, int bits) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            String rawStr = DatatypeConverter.printHexBinary(md.digest());
            if (bits == 32) return rawStr;

            bits = Math.min(32, bits);
            bits = Math.max(1, bits);

            int start;
            if (bits % 2  == 1) {
                start = (32 - bits + 1) / 2;
            } else {
                start = (32 - bits) / 2;
            }

            return rawStr.substring(start, start + bits);



        } catch (Exception e) {
            log.error("err", e);
            throw new RuntimeException("MD5加密出现错误，"+e.toString());
        }
    }

    public static String getMD5(String str) {
        return getMD5(str, 32);
    }
}
